import { defineStore } from "pinia";
import { login } from "../api/api";

export const useStore = defineStore('user', {
  state: () => ({
    userToken: undefined,
    id: '',
    name: '',
    email: '',
    //
    photo: '',
    signature: '',
    sex: '',
    phone: '',
    address: '',
    birth: '',
    admin: false
  }),
  getters: {
    // double: (state) => state.count * 2,
  },
  actions: {
    // 初始化store 使用结构体给store赋值
    initStore(userInfo) {
      this.userToken = userInfo.userToken
      this.id = userInfo.id
      this.name = userInfo.name
      this.email = userInfo.email
      this.photo = userInfo.photo
      this.signature = userInfo.signature
      this.sex = userInfo.sex
      this.phone = userInfo.phone
      this.address = userInfo.address
      this.birth = userInfo.birth
      this.getAdmin()
    },
    // 获取store的所有信息 返回一个结构体
    getStore() {
      return {
        userToken: this.userToken,
        id: this.id,
        name: this.name,
        email: this.email,
        photo: this.photo,
        signature: this.signature,
        sex: this.sex,
        phone: this.phone,
        address: this.address,
        birth: this.birth
      }
    },
    // 判断是否为管理员
    getAdmin() {
      if (this.userToken) {
        login(this.id).then(response => {
          if (response.data.admin) {
            this.admin = true
            return true
          }
        }).catch(error => console.log(error))
      }
      this.admin = false
      return false
    }
  },
})